﻿using Gma.QrCodeNet.Encoding;
using System;
using System.Drawing;
using System.IO;
using System.Windows;
using System.Windows.Media.Imaging;

namespace GenerateQR
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private Bitmap GetQRBitmap(string content)
        {
            var qrEncoder = new QrEncoder();
            var code = qrEncoder.Encode(content);
            var bitmapImage = new Bitmap(code.Matrix.Width, code.Matrix.Height);

            for (int j = 0; j < code.Matrix.Height; j++)
                for (int i = 0; i < code.Matrix.Width; i++)
                    bitmapImage.SetPixel(i, j, code.Matrix[i, j] ? System.Drawing.Color.Black : System.Drawing.Color.White);

            return bitmapImage;
        }

        private BitmapImage BitmapToImageSource(Bitmap bitmap)
        {
            using (MemoryStream memory = new MemoryStream())
            {
                bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
                memory.Position = 0;
                BitmapImage bitmapimage = new BitmapImage();
                bitmapimage.BeginInit();
                bitmapimage.StreamSource = memory;
                bitmapimage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapimage.EndInit();

                return bitmapimage;
            }
        }

        private void txtCode_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtCode.Text)) return;

            //QrCodeImgControl
            qrControl.Text = txtCode.Text;

            //Image
            var imageSource = BitmapToImageSource(GetQRBitmap(txtCode.Text));
            this.imgQR.Width = imageSource.PixelWidth;
            this.imgQR.Height = imageSource.PixelHeight;
            this.imgQR.Source = imageSource;
            this.imgQR.UpdateLayout();
        }

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            string path = Guid.NewGuid().ToString() + ".png";

            using (FileStream fileStream = new FileStream(path, FileMode.Create))
            {
                PngBitmapEncoder pngBitmapEncoder = new PngBitmapEncoder();
                pngBitmapEncoder.Frames.Add(BitmapFrame.Create((WriteableBitmap)qrControl.Source));
                pngBitmapEncoder.Save(fileStream);
                fileStream.Close();
            }
        }
    }
}